package com.lhn.formssi.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.lhn.formssi.service.RedisService;
import com.lhn.formssi.util.RedisUtil;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Service
public class RedisServiceImpl implements RedisService {
	
	@Autowired
    private JedisPool jedisPool;
	
	private Jedis getResource() {
        return jedisPool.getResource();
    }
	
    private void returnResource(Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }
	
	@Override
	public <T> T get(RedisUtil prefix, String key, Class<T> clazz) {
		// TODO Auto-generated method stub
		Jedis jedis = null;
		try {
			jedis = getResource();
			String str = jedis.get(prefix.getPrefix() + key);
	        return JSON.parseObject(str, clazz);
		} finally {
			// TODO: handle finally clause
			returnResource(jedis);
		}
	}

	@Override
	public <T> boolean set(RedisUtil prefix, String key, T value) {
		// TODO Auto-generated method stub
		if (value == null || key == null) {
            return false;
        }
		Jedis jedis = null;
		try {
			jedis = getResource();
            if (prefix.getExpireSeconds() <= 0) {
                jedis.set(prefix.getPrefix() + key, JSON.toJSONString(value));
            } else {
                // 设置有效期
                jedis.setex(prefix.getPrefix() + key, prefix.getExpireSeconds(), JSON.toJSONString(value));
            }
            return true;
		} finally {
			// TODO: handle finally clause
			returnResource(jedis);
		}
	}

	@Override
	public boolean exists(RedisUtil prefix, String key) {
		// TODO Auto-generated method stub
		if (key == null) {
            return false;
        }
        Jedis jedis = null;
        try {
            jedis = getResource();
            return jedis.exists(prefix.getPrefix() + key);
        } finally {
            returnResource(jedis);
        }
	}

	@Override
	public Long incr(RedisUtil prefix, String key) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Long decr(RedisUtil prefix, String key) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean delete(RedisUtil prefix, String key) {
		// TODO Auto-generated method stub
		Jedis jedis = null;
        try {
            jedis = getResource();
            return jedis.del(prefix.getPrefix() + key) > 0;
        } finally {
            returnResource(jedis);
        }
	}

}
